﻿using System.Text;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Encodings;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.OpenSsl;

namespace TenantSecurityProvider.Utils;

/// <summary>
/// RSA 加密工具类
/// </summary>
internal abstract class RsaDecryptUtils
{
    /// <summary>
    /// 加密
    /// </summary>
    /// <param name="content">加密内容</param>
    /// <param name="publicKey">公钥</param>
    /// <returns></returns>
    internal static string Encrypt(string content, string publicKey)
    {
        var bytes = Encoding.UTF8.GetBytes(content);

        var sb = new StringBuilder(130);
        using (var stringReader = new StringReader(publicKey))
        {
            var encryptEngine = new Pkcs1Encoding(new RsaEngine());
            var keyParameter = (AsymmetricKeyParameter)new PemReader(stringReader).ReadObject();
            encryptEngine.Init(true, keyParameter);
            var offset = 0;
            while (offset < bytes.Length)
            {
                var bytesToEncrypt = new byte[Math.Min(117, bytes.Length - offset)];
                Array.Copy(bytes, offset, bytesToEncrypt, 0, bytesToEncrypt.Length);
                sb.Append(Convert.ToBase64String(encryptEngine.ProcessBlock(bytesToEncrypt, 0, bytesToEncrypt.Length)));
                sb.Append('|');
                offset += 117;
            }
        }

        return sb.ToString().TrimEnd('|');
    }
}
